﻿Imports System.Data
Imports ADOEntity

Partial Class Administrator_userExpireReport
    Inherits Web.UI.BasePage
    Private Const strMenuCode As String = "M67"
    Dim userExpireEntity As New userEntities
    Dim dsUserExpire As New DataSet
    Dim clsDataTable As New clsLINQToDataTable
    Dim clsSessionMenuRight As clsSessionMenuRight
    Dim systemConfigEntity As New systemConfigEntities

    Dim expirePWDAdmin As Integer
    Dim expirePWDUser As Integer
    Dim expireDateUser As Integer
    Dim defaultPWD As String
    Dim clsFormatDate As clsDateFormat
    Dim clsMasterDropDown As clsMasterDropDown
    Dim clsDatabase As clsDatabase

#Region " Even Page "
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        btnSearch.Text = Resources.resButton.btnSearch
        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            chkIsLogin()
            clsMasterDropDown = New clsMasterDropDown
            clsSessionMenuRight = Session("clsMenuRight")
            If (Not IsPostBack) Then
                LoadDataToDropdown()
                setDefaultSearch()
                setUserRightButton()
                chkIsLogin()
                CreateControlMP()
            Else
                dsUserExpire = Session("dsTblMaster")
            End If
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsTblMaster") = dsUserExpire
    End Sub

#End Region

#Region "SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "รายงานการปลดล็อคผู้ใช้งาน/รหัสผ่าน"
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        Try
            'If ddlType.SelectedIndex = 0 Then
            '    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('กรุณาเลือก ประเภทปลดล็อค')", True)
            '    Exit Sub
            'Else
            IsDataBind()
            clearGvIndex()
            'End If
        Catch ex As Exception

        End Try


    End Sub

    Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Dim param As String = "{ 'rptType' : '7'," _
                              & "'startDate' : '" & txtStartDate.Text & "'," _
                              & "'endDate' : '" & txtEndDate.Text & "'," _
                              & "'deptCode' : '" & ddlDepartMent.SelectedValue & "/" & ddlDepartMent.SelectedItem.Text & "'," _
                              & "'BranchCode' : '" & ddlBranch.SelectedValue & "/" & ddlBranch.SelectedItem.Text & "'," _
                              & "'userRight' : '" & ddlUserRight.SelectedValue & "/" & ddlUserRight.SelectedItem.Text & "'," _
                              & "'userName' : '" & txtUserName.Text.Trim & "'," _
                              & "'empName' : '" & txtFirstName.Text.Trim & "'," _
                              & "'empLastName' : '" & txtLastName.Text.Trim & "'," _
                              & "'lockType' : '" & ddlType.SelectedValue & "/" & ddlType.SelectedItem.Text & "'}"

        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType, "key", "OpenWindowWithPost('../Form/frmPrintRptMaster.aspx','width=730,height=345,left=100,top=100,resizable=yes,scrollbars=yes','Report', " + param + ");", True)
    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        ddlType.SelectedIndex = 0
        ddlDepartMent.SelectedIndex = 0
        ddlBranch.SelectedIndex = 0
        ddlUserRight.SelectedIndex = 0
        txtStartDate.Text = ""
        txtEndDate.Text = ""
        txtUserName.Text = ""
        txtFirstName.Text = ""
        txtLastName.Text = ""
        setDefaultSearch()
        gvUserExpire.DataSource = Nothing
        gvUserExpire.DataBind()
    End Sub

#End Region

#Region "Even GridView"

    Protected Sub gvUserExpire_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvUserExpire.PageIndexChanging
        gvUserExpire.PageIndex = e.NewPageIndex
        gvUserExpire.DataSource = dsUserExpire.Tables("UserExpire")
        gvUserExpire.DataBind()
        clearGvIndex()
    End Sub
    Protected Sub gvUserExpire_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvUserExpire.Sorting
        Dim dt = TryCast(dsUserExpire.Tables("UserExpire"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            gvUserExpire.DataSource = dsUserExpire.Tables("UserExpire")
            gvUserExpire.DataBind()
            clearGvIndex()
        End If
    End Sub

    Protected Sub chkAll_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim chk As CheckBox = CType(gvUserExpire.HeaderRow.FindControl("chkAll"), CheckBox)
        If (chk.Checked) Then
            For i As Int16 = 0 To gvUserExpire.Rows.Count - 1
                Dim chkrow As CheckBox = CType(gvUserExpire.Rows(i).FindControl("chkSelect"), CheckBox)
                chkrow.Checked = True

            Next
        Else

            For i As Int16 = 0 To gvUserExpire.Rows.Count - 1
                Dim chkrow As CheckBox = CType(gvUserExpire.Rows(i).FindControl("chkSelect"), CheckBox)
                chkrow.Checked = False

            Next

        End If

    End Sub


    Protected Sub chkSelect_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        'If gvUserExpire.SelectedIndex > -1 Then
        '    Dim chkrow As CheckBox = CType(gvUserExpire.Rows(gvUserExpire.SelectedIndex).FindControl("chkSelect"), CheckBox)
        '    If chkrow.Checked = False Then
        '        Dim chk As CheckBox = CType(gvUserExpire.HeaderRow.FindControl("chkAll"), CheckBox)
        '        chk.Checked = False
        '    End If
        'End If

        For i As Int16 = 0 To gvUserExpire.Rows.Count - 1
            Dim chkrow As CheckBox = CType(gvUserExpire.Rows(i).FindControl("chkSelect"), CheckBox)
            If chkrow.Checked = False Then
                Dim chk As CheckBox = CType(gvUserExpire.HeaderRow.FindControl("chkAll"), CheckBox)
                chk.Checked = False
                Exit For
            End If
        Next


    End Sub

#End Region

#Region " Function"

    Public Sub setDefaultSearch()
        clsFormatDate = New clsDateFormat
        txtStartDate.Text = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.Th, dteDateIsChk:=Date.Now)
        txtEndDate.Text = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.Th, dteDateIsChk:=Date.Now)



    End Sub

    Private Sub setUserRightButton()
        Dim col As New Collection
        col.Add(btnSearch, statusbtn.Query.ToString)
        col.Add(btnPrint, statusbtn.print.ToString)
        setBtnToUserRight(col, strMenuCode, clsSessionMenuRight.getDsMenuRight)

    End Sub
    Private Sub LoadDataToDropdown()
        Dim clsSessionMenuRight As clsSessionMenuRight
        clsSessionMenuRight = Session("ClsMenuRight")

        'clsMasterDropDown.setUserRightToDdlSearch(ddlUserRight)

        'clsMasterDropDown.setDeptToDdlSearch(ddlDepartMent, _
        '                                 strDeptCode:=clsSessionMenuRight.getDeptCode, _
        '                                 strRoleCode:=clsSessionMenuRight.getRoleGroup)

        'clsMasterDropDown.setBranchDdlSearch(ddlBranch, strDeptCode:=ddlDepartMent.SelectedValue, _
        '                                           strBranchCode:=clsSessionMenuRight.getBranchCode, _
        '                                     strRoleCode:=clsSessionMenuRight.getRoleGroup, _
        '                                     strZoneCode:=clsSessionMenuRight.getZoneCode)

        clsMasterDropDown.setDeptToDdlSearch(ddlDepartMent, _
                                        strDeptCode:=clsSessionMenuRight.getDeptCode, _
                                        strRoleCode:=clsSessionMenuRight.getRoleGroup)

        clsMasterDropDown.setUserRightToDdlSearch(ddlUserRight, clsSessionMenuRight.getRoleGroup, strDepCode:=ddlDepartMent.SelectedValue)

        clsMasterDropDown.setBranchDdlSearch(ddlBranch, strDeptCode:=ddlDepartMent.SelectedValue, _
                                                   strBranchCode:=clsSessionMenuRight.getBranchCode, _
                                             strRoleCode:=clsSessionMenuRight.getRoleGroup, _
                                             strZoneCode:=clsSessionMenuRight.getZoneCode)
    End Sub

    Private Sub clearGvIndex()
        gvUserExpire.SelectedIndex = -1


    End Sub

    Private Sub IsDataBind()
        Dim clsSessionMenuRight As New clsSessionMenuRight
        Dim clsFormatDate As New clsDateFormat
        clsSessionMenuRight = Session("ClsMenuRight")

        If dsUserExpire.Tables.Contains("UserExpire") Then
            dsUserExpire.Tables.Remove("UserExpire")
        End If

        'Dim qryUserExpire = From pwdExpire In userExpireEntity.SUSER Join Branch In userExpireEntity.SBRANCH On pwdExpire.BRANCHCODE Equals Branch.BRANCHCODE Join dept In userExpireEntity.SDEPARTMENT On pwdExpire.DEPTCODE Equals dept.DEPTCODE _
        '                   Order By pwdExpire.USERNAME _
        Dim qryUserExpire = From hist In userExpireEntity.H_UNLOCKUSER
                            Join user In userExpireEntity.SUSER On hist.USERNAMELOCK Equals user.USERNAME
                            Join userUnlock In userExpireEntity.SUSER On hist.USERNAMEUNLOCK Equals userUnlock.USERNAME
                            Join Branch In userExpireEntity.SBRANCH On user.BRANCHCODE Equals Branch.BRANCHCODE Join dept In userExpireEntity.SDEPARTMENT On user.DEPTCODE Equals dept.DEPTCODE _
                           Order By user.USERNAME _
                           Select user.USERNAME, EmpFullName = user.EMPNAME & " " & user.EMPLASTNAME, _
                           user.EMPNAME, user.EMPLASTNAME, Branch.BRANCHNAME, dept.DEPTNAME, user.LASTLOGINDATE, user.ISLOGIN, _
                           UNLOCKER = userUnlock.USERNAME,
        hist.DATEUNLOCK, hist.REASONCODE, hist.REASONTXT,
        user.USEREXPIREDATE, user.ISUSEREXPIRE,
        user.PWDEXPIREDATE, user.ISPWDEXPIRE,
        user.DEPTCODE, user.ROLECODE, user.ZONECODE, user.USERRIGHT, user.LASTIP, user.BRANCHCODE


        If (clsSessionMenuRight.getRoleGroup > 89) Then
        ElseIf (clsSessionMenuRight.getRoleGroup > 79) Then
            qryUserExpire = qryUserExpire.Where(Function(fn) fn.ROLECODE < clsSessionMenuRight.getRoleGroup)
        ElseIf (clsSessionMenuRight.getRoleGroup > 69) Then
            qryUserExpire = qryUserExpire.Where(Function(fn) fn.ROLECODE < clsSessionMenuRight.getRoleGroup)
        ElseIf (clsSessionMenuRight.getRoleGroup > 59) Then
            qryUserExpire = qryUserExpire.Where(Function(fn) fn.ROLECODE < clsSessionMenuRight.getRoleGroup And fn.ZONECODE = clsSessionMenuRight.getZoneCode)
        ElseIf (clsSessionMenuRight.getRoleGroup < 60) Then
            qryUserExpire = qryUserExpire.Where(Function(fn) fn.ROLECODE < clsSessionMenuRight.getRoleGroup)
        End If



        Dim dteDateNow As Date = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, dteDateIsChk:=Date.Now)
        If Not ddlType.SelectedIndex = 0 Then
            qryUserExpire = qryUserExpire.Where(Function(hist) hist.REASONCODE = ddlType.SelectedValue)
        End If

        If Not (txtStartDate.Text = "" And txtEndDate.Text = "") Then
            Dim strStartDate As String = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, txtStartDate.Text) & " 00:00:00"
            Dim strEndDate As String = clsFormatDate.chkDateThOrEn(clsDateFormat.enmDateCultureInfo.En, txtEndDate.Text) & " 23:59:59"
            qryUserExpire = qryUserExpire.Where(Function(hist) hist.DATEUNLOCK >= strStartDate And hist.DATEUNLOCK <= strEndDate)
        End If

        If Not (txtUserName.Text = "") Then
            qryUserExpire = qryUserExpire.Where(Function(pwdLock) pwdLock.USERNAME.Contains(txtUserName.Text))
        End If

        If Not (txtFirstName.Text = "") Then
            qryUserExpire = qryUserExpire.Where(Function(pwdLock) pwdLock.EMPNAME.Contains(txtFirstName.Text))
        End If

        If Not (txtLastName.Text = "") Then
            qryUserExpire = qryUserExpire.Where(Function(pwdLock) pwdLock.EMPLASTNAME.Contains(txtLastName.Text))
        End If

        If Not ddlDepartMent.SelectedValue = "0" Then
            qryUserExpire = qryUserExpire.Where(Function(dep) dep.DEPTCODE = ddlDepartMent.SelectedValue)
        End If

        If Not ddlBranch.SelectedValue = "0" Then
            qryUserExpire = qryUserExpire.Where(Function(branch) branch.BRANCHCODE = ddlBranch.SelectedValue)
        End If

        If Not ddlUserRight.SelectedValue = "0" Then
            qryUserExpire = qryUserExpire.Where(Function(userRight) userRight.USERRIGHT = ddlUserRight.SelectedValue)
        End If

        dsUserExpire.Tables.Add(clsDataTable.LINQToDataTable(qryUserExpire, "UserExpire").Copy)

        If (qryUserExpire.Count = 0) Then
            lblMsg.Visible = True
        Else
            lblMsg.Visible = False

        End If

        gvUserExpire.DataSource = dsUserExpire.Tables("UserExpire")
        gvUserExpire.DataBind()
        clsDataTable = Nothing
    End Sub

    Private Function GetSortDirection(ByVal column As String) As String

        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"

        ' Retrieve the last column that was sorted.
        Dim sortExpression = TryCast(ViewState("SortExpression"), String)

        If sortExpression IsNot Nothing Then
            ' Check if the same column is being sorted.
            ' Otherwise, the default value can be returned.
            If sortExpression = column Then
                Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                If lastDirection IsNot Nothing _
                  AndAlso lastDirection = "DESC" Then

                    sortDirection = "ASC"

                End If
            End If
        End If

        ' Save new values in ViewState.
        ViewState("SortDirection") = sortDirection
        ViewState("SortExpression") = column
        Return sortDirection
    End Function

    Private Sub setConfig()
        Dim qry = (From systemConfig In systemConfigEntity.SSYSTEMCONFIG
                             Order By systemConfig.CONFIGINDEX).ToList

        expirePWDAdmin = qry(0).CONFIGNUM
        expirePWDUser = qry(1).CONFIGNUM
        expireDateUser = qry(6).CONFIGNUM
        defaultPWD = qry(7).CONFIGSTR

        qry = Nothing

    End Sub

    Private Sub savePWDLOCKDATE(ByVal username As String) 'login เกิน
        Dim updateUser = (From u In userExpireEntity.SUSER
                        Where u.USERNAME = username
                        Select u).First()

        updateUser.ISPWDLOCK = 0
        updateUser.PWDLOCKDATE = Nothing
        updateUser.CURRENTLOCKNUM = 0
        updateUser.PASSWORD = defaultPWD
        updateUser.MUSTCHANGEPWD = 1
        If updateUser.ROLECODE < 50 Then
            updateUser.PWDEXPIREDATE = Date.Now.AddDays(expirePWDUser).ToShortDateString
        Else
            updateUser.PWDEXPIREDATE = Date.Now.AddDays(expirePWDAdmin).ToShortDateString
        End If
        updateUser.UPDATEBY = clsSessionMenuRight.getUserName
        updateUser.UPDATEDATE = Now.ToShortDateString

    End Sub

    Private Sub saveISUSEREXPIRE(ByVal username As String) 'ผู้ใช้หมดอายุ
        Dim updateUser = (From u In userExpireEntity.SUSER
                        Where u.USERNAME = username
                        Select u).First()

        updateUser.ISUSEREXPIRE = 0
        updateUser.USEREXPIREDATE = Date.Now.AddDays(expireDateUser).ToShortDateString
        updateUser.UPDATEBY = clsSessionMenuRight.getUserName
        updateUser.UPDATEDATE = Now.ToShortDateString

    End Sub

    Private Sub saveISPWDEXPIRE(ByVal username As String) 'รหัสผ่านหมดอายุ
        Dim updateUser = (From u In userExpireEntity.SUSER
                        Where u.USERNAME = username
                        Select u).First()

        updateUser.ISPWDEXPIRE = 0

        If updateUser.ROLECODE < 50 Then
            updateUser.PWDEXPIREDATE = Date.Now.AddDays(expirePWDUser).ToShortDateString
        Else
            updateUser.PWDEXPIREDATE = Date.Now.AddDays(expirePWDAdmin).ToShortDateString
        End If

        updateUser.PASSWORD = defaultPWD
        updateUser.MUSTCHANGEPWD = 1
        updateUser.UPDATEBY = clsSessionMenuRight.getUserName
        updateUser.UPDATEDATE = Now.ToShortDateString

    End Sub

    Private Sub saveIsLogin(ByVal username As String) 'login เกิน
        Dim updateUser = (From u In userExpireEntity.SUSER
                        Where u.USERNAME = username
                        Select u).First()
        updateUser.ISLOGIN = False
    End Sub
#End Region

    Protected Sub ddlDepartMent_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlDepartMent.SelectedIndexChanged
        'Dim clsDropDown As New clsMasterDropDown
        ''clsSessionMenuRight = Session("ClsMenuRight")
        'If Not (ddlDepartMent.SelectedValue = "0") Then
        '    clsDropDown.setBranchDdlSearch(ddlBranch, strDeptCode:=ddlDepartMent.SelectedValue, strBranchCode:=clsSessionMenuRight.getBranchCode, strRoleCode:=clsSessionMenuRight.getRoleGroup, strZoneCode:=clsSessionMenuRight.getZoneCode)
        'Else
        '    ddlBranch.SelectedValue = "0"
        'End If

        'clsDropDown = Nothing
        Dim clsDropDown As New clsMasterDropDown
        clsSessionMenuRight = Session("ClsMenuRight")
        If Not (ddlDepartMent.SelectedValue = "0") Then
            clsDropDown.setBranchDdlSearch(ddlBranch, strDeptCode:=ddlDepartMent.SelectedValue, strBranchCode:=clsSessionMenuRight.getBranchCode, strRoleCode:=clsSessionMenuRight.getRoleGroup, strZoneCode:=clsSessionMenuRight.getZoneCode)
            'clsMasterDropDown.setUserRightToDdlSearch(ddlUserRight, clsSessionMenuRight.getRoleGroup)

            clsDropDown.setUserRightToDdlSearch(ddlUserRight, strRoleCode:=clsSessionMenuRight.getRoleGroup, strDepCode:=ddlDepartMent.SelectedValue)
        Else
            clsDropDown.setBranchDdlSearch(ddlBranch, strDeptCode:=ddlDepartMent.SelectedValue, strBranchCode:=clsSessionMenuRight.getBranchCode, strRoleCode:=clsSessionMenuRight.getRoleGroup, strZoneCode:=clsSessionMenuRight.getZoneCode)
            clsDropDown.setUserRightToDdlSearch(ddlUserRight, strRoleCode:=clsSessionMenuRight.getRoleGroup)
            ddlBranch.SelectedValue = "0"
            ddlUserRight.SelectedValue = "0"
        End If

    End Sub

    Private Function GetUnlockUserHistId() As Decimal
        clsDatabase = New clsDatabase
        Dim sql As String = "select KYCADMIN.H_UNLOCKUSER_S.nextval from dual"
        Dim seq As Integer = clsDatabase.QueryDataTable(sql).Rows(0)("NEXTVAL")
        Return seq
    End Function

    Protected Sub InsertHist(ByVal reasonCode As String, ByVal reasonTxt As String, ByVal userName As String)
        clsSessionMenuRight = Session("ClsMenuRight")

        Dim hist = New H_UNLOCKUSER
        hist.SYS_ID = GetUnlockUserHistId()
        hist.REASONCODE = reasonCode
        hist.REASONTXT = reasonTxt
        hist.USERNAMELOCK = userName
        hist.USERNAMEUNLOCK = clsSessionMenuRight.getUserName
        hist.DATEUNLOCK = DateTime.Now

        userExpireEntity.AddToH_UNLOCKUSER(hist)
    End Sub

    
End Class
